/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cliente.responsehandler.xml;

import cliente.auxiliar.GereErros;
import cliente.domain.Status;
import cliente.parsing.XmlParsingUtils;
import cliente.responsehandler.DocumentParseException;
import java.io.IOException;
import java.util.Vector;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.xmlpull.mxp1.MXParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

/**
 *
 * @author ziza
 */
public class XmlUserTweetsResponseHandler implements ResponseHandler<Vector<Status>> {

    GereErros erro = null;

    public XmlUserTweetsResponseHandler(GereErros erro) {
        this.erro = erro;
    }

    public Vector<Status> handleResponse(HttpResponse httpResponse) throws IOException {

        Vector<Status> respostaOp = new Vector<Status>();

        if (httpResponse.getStatusLine().getStatusCode() != 200) {
            erro.trataErros(httpResponse);
        }

        XmlPullParser xpp = new MXParser();
        Status satus = null;
        try {
            xpp.setInput(httpResponse.getEntity().getContent(), null);
            xpp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);

            int eventType = xpp.getEventType();
            String eventName = xpp.getName();

            while(eventType != XmlPullParser.END_DOCUMENT) {
                eventType = xpp.next();
                eventName = xpp.getName();
                //System.out.println("Event Type:"+eventName);
                
                if (eventType == XmlPullParser.START_TAG) {
                    if ("status".equals(eventName)) {
                        //System.out.println("Entra aqui carago!!!");
                        satus = XmlParsingUtils.parseStatus(xpp);
                        //System.out.println("--TWEET:"+satus.getText());
                        respostaOp.add(satus);
                    }
                }        
            }
            //System.out.println("Tamanho:"+respostaOp.size()+" - "+respostaOp.get(2).getText());
        } catch (XmlPullParserException e) {
            // wrap exception and propagate it upwards
            System.out.println("Erro:"+e.getMessage());
            throw new DocumentParseException(e);
        }

        if (satus == null) {
            System.err.println("Warning! Failed to parse XML to create a valid User!");
            // Remember to check in your code if the result of this response handler is not null.
            // When you reach the daily API call limit, Twitter will reply with empty bodies.
            // Another alternative would be to throw an Exception, e.g.: DailyLimitExceededException
        }
        return respostaOp;

    }

}
